﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using ERP.Business.DataTypes.Users.Credentials;
using ERP.Framework.Components.DatabaseHelper.Providers;
using ERP.Framework.Components.DatabaseHelper;
using ERP.Framework.Components.Utilities.TracingHelper;

namespace ERP.Business.Services.Users
{
    /// <summary>
    /// CredentialsManager service
    /// </summary>
    public class CredentialsService : ICredentialsService
    {
        #region Constans

        private const string TRACING_CATEGORY = "ERP.Business.Services.Users.CredentialsManagement.CredentialsManager";
        private const string CHECK_USER_CREDENTIALS_SP = "SP_USERS_CHECK_CREDENTIALS";
        private const string PARAM_USERNAME = "@username";
        private const string PARAM_PASSWORD = "@password";
        private const string PARAM_MODULE_ID = "@module_id";

        #endregion

        /// <summary>
        /// Get user's credentials for a certain module
        /// </summary>
        /// <param name="username">username</param>
        /// <param name="password">password</param>
        /// <param name="moduleID">module id</param>
        /// <returns><see cref="CredentialStatus"/></returns>
        public CredentialStatus GetUserCredential(string username, string password, string moduleID)
        {
            TraceUtil.Write(TRACING_CATEGORY, "GetUserCredential : Start", DateTime.Now);  
            CredentialStatus cresult = CredentialStatus.AccessDenied;

            GeneralDatabaseProvider con = new GeneralDatabaseProvider(DatabaseConstants.AdministrationDatabase);
            ParametersCollection p = new ParametersCollection();
            p.AddParameter(new Parameter(PARAM_USERNAME, username, ParameterType.String));
            p.AddParameter(new Parameter(PARAM_PASSWORD, password, ParameterType.String));
            p.AddParameter(new Parameter(PARAM_MODULE_ID, moduleID, ParameterType.String));
            object result = con.ReadScalar(ERP.Framework.Components.DatabaseHelper.CommandType.StoredProcedure, CHECK_USER_CREDENTIALS_SP, p);
            bool bolRes = false;

            if (result != null && bool.TryParse(result.ToString(), out bolRes) && bolRes)
            {
                //set initial credentioal to ReadOnly
                cresult = CredentialStatus.ReadOnly;
            }

            TraceUtil.Write(TRACING_CATEGORY, "GetUserCredential : End", DateTime.Now);  
            return cresult;
        }
    }
}